package com.jn.singleton.type6;

/**
 * 双重检查
 * @author 江南大学1033190417
 * @date 2022/4/10 15:59
 */
public class SingletonTest3 {
    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance1 == instance);//true
        System.out.println(instance.hashCode());
        System.out.println(instance1.hashCode());//相同
    }
}

class Singleton {

    private static volatile Singleton instance;

    private Singleton() {
    }

    //双重检查,解决线程安全和懒加载问题
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null)
                    instance = new Singleton();
            }
        }
        return instance;
    }

}
